import {objectIsEq, resetLongToStr} from "@/utils/biz/common/BizUtils";
import {AndroidSDK} from "@/sdk/AndroidSdkService";
import {Observer} from "@/utils/observer/Observer";
import {Message} from 'element-ui';
import {UserCommitApi, XinYuShiCommitApi, TongXiangShiCommitApi} from "@/api/user_common";

/**
 * 报到机 扫码逻辑
 */
class MachineObserverBiz extends Observer {
    constructor(self, deviceInfo = {}, item) {
        super();
        // 外部组件
        this.catcheInfo = self;
        // 设备信息
        this.deviceInfo = deviceInfo;
        // 当前组件信息
        this.currentInfo = item || {};
    }

    /**
     * 消息监听入口
     * @param bizType
     * @param msgContent
     */
    async update(bizType, msgContent) {
        let self = this.catcheInfo;
        try {
            switch (bizType) {
                // 安卓调用扫码报到
                case "cardInfoCallBack":
                    await this.cardInfoCallBack(msgContent);
                    break;
                // 报到机 -- 处理报到成功
                case "reportResult":
                    await this.dealReportData(msgContent);
                    break;
                // 安卓自己报到后 回传的报到数据
                case "reportQuery":
                    await this.setReportPatientInfo(msgContent);
                    break;
            }
        } catch (e) {
            console.error("消息数据加载失败：" + msgContent)
            self.handleException("sdkBizServices", `安卓消息消费异常:${bizType}${JSON.stringify(e.stack)}`);
        }

    }

    /**
     * 页面自定义消息入口
     * @returns {Promise<void>}
     * @param options
     */
    async msgEvent(options = {}) {
        const {bizType, data} = options;
        let self = this.catcheInfo;
        switch (bizType) {
            // 模板点击事件 -- 扫码查询s
            case "handleInput":
                self.currentInitParams = {
                    cardType: 0
                }
                // 适配电子医保凭证
                let environment = AndroidSDK.environment;
                if (environment && 'dotnet' === environment) {
                    await this.handleHiddenSubmit(data)
                }else {
                    await this.initSign({
                        patientNo: data.number
                    }, true);
                }
                break;
            case "openReadCardScan":
                self.patientNo = "";
                // 开启安卓读卡
                this.openReadCardScan();
                // 关闭非预约弹窗弹窗
                this.closeReportSurePower();
                // 关闭弹窗 -- 选择科室
                this.closeReportDept();
                break;
            // 模板点击事件 -- 单个报到
            case "toReport":
                await this.toReport(data);
                break;
            // 模板点击事件 -- 批量报到
            case "reportAll":
                await this.reportAll(data, 2);
                break;
            // 模板点击事件 -- 复诊报到
            case "repeatReport":
                await this.repeatReport(data);
                break;
            // 进入下级页面
            case "goToNext":
                await this.goToNext(data);
                break;
            // 取号机扫码
            case "goToInitSignBiz":
                await this.goToInitSignBiz(data);
                break;
            // 取号机扫码
            case "handleHiddenSubmit":
                await this.handleHiddenSubmit(data);
                break;
        }
    }


    /**
     * 初始化
     */
    async init() {
        await this.getAllBizAttr();
        // 只有是 dotnet window 环境才会请求
        let environment = AndroidSDK.environment;
        if (environment && 'dotnet' === environment) {
            // 获取医保码配置
            await this.getSystemConfigByKey({
                key: "Nation",
                tenantId: this.deviceInfo.tenantId || "000000"
            })
        }
    }

    /**
     * 获取配置
     * @param key
     */
    async getSystemConfigByKey(key) {
        let self = this.currentInfo;
        try {
            const {code, data} = await UserCommitApi.getSystemConfig(key);
            if (200 === parseInt(code)) {
                let configValue = JSON.parse(data.configValue);
                self.yiBaoInfo = configValue;
                self.isOpenYiBao = data.hasOpen;
            }
        } catch (e) {
            self.handleException("sdkServices", "getSystemConfigByKey -->获取全局配置失败", JSON.stringify(e.stack));
        }
    }

    /**
     * 获取业务类型
     */
    async getAllBizAttr() {
        let self = this.catcheInfo;
        try {
            let formData = {
                terminalId: this.deviceInfo.screenId,
                terminalType: this.deviceInfo.screenType,
                businessType: this.deviceInfo.businessType,
            };
            const {code, data} = await UserCommitApi.getAllBizAttr(formData);
            if (200 === parseInt(code)) {
                self.bizAttrList = data || [];
                if (this.currentInfo?.screenDataType.indexOf("reportPickNumber") > -1) {
                    if (self.bizAttrList.length === 0) {
                        await this.getBizObjList();
                    } else {
                        this.setBizAttrList();
                    }
                }
            }
        } catch (e) {
            self.handleException("sdkServices", "getModelDetail --> 获取模板或解析模板数据异常异常", JSON.stringify(e.stack));
        }
    }

    /**
     * 获取号别
     */
    async getBizObjList() {
        let self = this.catcheInfo;
        try {
            let formData = {
                terminalId: this.deviceInfo.screenId,
                terminalType: this.deviceInfo.screenType,
                businessType: this.deviceInfo.businessType,
                tenantId: this.deviceInfo.tenantId || "000000"
            };
            const {code, data} = await UserCommitApi.getBizObjList(formData);
            if (200 === parseInt(code)) {
                self.bizObjList = data || [];
                self.bizObjList.forEach((item) => {
                    self.bizAttrList.push({
                        title: item.registerObjName,
                        titleShort: item.registerObjSimpleName,
                        ruleType: item.ruleType,
                        registerObjId: item.registerObjId,
                        registerObjInfo: item,
                        tackNoType: item.tackNoType
                    });
                });
                this.setBizAttrList();
            }
        } catch (e) {
            self.handleException("sdkServices", "getBizObjList --> 获取号别数据异常", JSON.stringify(e.stack));
        }
    }

    /**
     * 写入下拉数据
     */
    setBizAttrList() {
        let self = this.catcheInfo;
        try {
            const formRef = self.$refs["vFormRef"];
            if (formRef) {
                formRef.executeChildMethod(this.currentInfo?.id, "reportPickInfo", self.bizAttrList);
            }
        } catch (e) {
            self.handleException("sdkBizServices", "内部组件异常 -- reportPatientInfo -- >", JSON.stringify(e.stack));
        }
    }

    /**
     * 组装扫码参数
     * @param params
     */
    getInitSignRequestParams(params) {
        let self = this.catcheInfo;
        // 扫码
        let formData = {
            terminalId: this.deviceInfo.screenId,
            terminalType: this.deviceInfo.screenType,
            businessType: this.deviceInfo.businessType,
            tenantId: this.deviceInfo.hospitalId || "000000",
            patientNo: params.patientNo,
            cardType: self.currentInitParams.cardType,
            // 患者姓名可能不存在
            patientName: params.patientName || "",
            ruleType: this.deviceInfo.ruleType || "0",
            // 是否开启患者隐私保护 0否 1是
            isNameProtect: self.signInfo.isNameProtect,
            // 诊结数据查询 0否 1是
            isTreatEndPatient: self.signInfo.isTreatEndPatient
        };
        // 设置其他业务属性参数
        let bizInfo = self.currentBizInfo;
        if (bizInfo == null && self.bizAttrList.length > 0) {
            bizInfo = self.bizAttrList[0];
        }
        if (bizInfo != null) {
            // 0:临床、1:医技 、2:业务 、3:药房
            formData["ruleType"] = bizInfo.ruleType || 0;
            // 策略KEY
            formData["bizKey"] = bizInfo.bizKey;
            // 业务ID
            formData["bizId"] = bizInfo.bizId;
            // 号别ID
            if (bizInfo.registerObjInfo) {
                formData["registerObjId"] = bizInfo.registerObjInfo.registerObjId;
            }
        }
        return formData;
    }

    /**
     *  安卓调用前端扫码接口
     *  数据结构{"cardId": "","name": "","sex": "","birth": ""}
     */
    async cardInfoCallBack(str) {
        let self = this.catcheInfo;
        try {
            let obj;
            if (objectIsEq(str, "String")) {
                obj = JSON.parse(resetLongToStr(str));
            } else {
                obj = str;
            }
            let isPass = true;
            if (obj.cardId === "") {
                switch (obj.cardType + "") {
                    case "8":
                        let extra = obj.extra;
                        if (objectIsEq(extra, "String")) {
                            extra = JSON.parse(resetLongToStr(extra));
                        }
                        if (extra.code !== "0") {
                            isPass = false;
                            this.openReportResultLayer({
                                title: "系统提示",
                                content: extra.message,
                                state: 0
                            });
                        }
                }
            }
            if (isPass === false) {
                return;
            }
            if (self.patientNo === obj.cardId) {
                return;
            }

            self.patientNo = obj.cardId;
            // 回到首页
            this.goHomePage();
            self.currentInitParams = {
                patientNo: obj.cardId,
                patientName: obj.name || "",
                cardType: obj.cardType
            }
            // 查询患者数据
            await this.initSign(self.currentInitParams, true);

        } catch (e) {
            AndroidSDK.writeLog("扫码报到异常 cardInfoCallBack--->" + JSON.stringify(e.stack));

            this.openReportResultLayer({
                title: "系统提示",
                content: "系统异常，请联系管理员",
                state: 0
            });
        }
    }

    /**
     * 安卓调用扫码接口
     * @param params
     * @param isShow
     * @returns {Promise<boolean>}
     */
    async initSign(params, isShow) {
        let self = this.catcheInfo;
        try {
            this.closeReportResultLayer();
            this.closeReportPatientLayer();
            // 关闭弹窗
            this.closeReportSurePower();
            this.closeReportDept();

            // 如果是多个业务，这里需要弹窗显示选择要办理的业务
            if (false === this.isShowBiz(params, isShow)) {
                return false;
            }
            // 组装扫码参数
            let formData = this.getInitSignRequestParams(params);
            // 获取扫码数据
            this.openPopupLoading();
            const res = await UserCommitApi.initSign(formData);
            this.closePopupLoading();
            // 关闭键盘
            this.closeKeyboard();

            if (200 === parseInt(res.code)) {
                // 有回调就不走通用逻辑 -- 业务取号
                if (res.data && "" === res.data.callBack) {
                    this.openReportResultLayer({
                        title: res.data && res.data.title ? res.data.title : "系统提示",
                        content: res.data?.msgTips || '',
                        state: 1
                    });
                    // 给安卓发送消息 安卓提供的能力
                    AndroidSDK.takeNumberTicket({
                        signId: res.data.signId,
                        ruleType: res.data.ruleType,
                        code: res.code
                    });
                } else {
                    // 发送扫码数据
                    await this.setReportPatientInfo(res);
                    // 本地一键报到
                    await this.reportAll(res.data, "1");
                }
            } else {
                // 接口数据异常
                this.openReportResultLayer({
                    state: 0,
                    title: res.data && res.data.patientName ? res.data.patientName : "系统提示",
                    content: res.msg,
                });
            }
            self.currentInitParams.cardType = 0;
        } catch (e) {
            // 异常关闭弹窗再
            this.closePopupLoading();

            AndroidSDK.writeLog("扫码报到异常 initSign--->" + JSON.stringify(e.stack));
            this.openReportResultLayer({
                title: "系统提示",
                content: "系统异常，请联系管理员",
                state: 0
            });
        } finally {
        }
    }

    /**
     * 取号机扫码
     */
    async initSignBiz(params) {
        let self = this.catcheInfo;
        if (self.currentBizInfo == null) {
            // 暂无任何数据时候或者接口异常提示
            this.openReportResultLayer({
                state: 0,
                title: "系统提示",
                content: "请选择要办理的业务",
                time: 5
            });
            self.currentPatient = params;
            return;
        }
        try {
            this.closePopupLoading();
            // 获取请求参数
            let formData = this.getInitSignRequestParams(params);
            // 执行取号逻辑
            const res = await UserCommitApi.initSign(formData);
            if (200 === parseInt(res.code)) {
                this.openReportResultLayer({
                    title: res.data && res.data.title ? res.data.title : "取号成功",
                    content: res.data && res.data.msgTips || res.msg,
                    state: 1,
                    time: 3
                });
                // 给安卓发送消息 安卓提供的能力
                AndroidSDK.takeNumberTicket({
                    signId: res.data.signId,
                    ruleType: res.data.ruleType,
                    code: res.code
                });
            } else {
                // 展示异常数据
                this.openReportResultLayer({
                    state: 0,
                    title: res.data && res.data.title || "取号失败",
                    content: res.data && res.data.msgTips || res.msg,
                    time: 3
                });
            }
        } catch (e) {
            AndroidSDK.writeLog("扫码报到异常 initSign--->" + JSON.stringify(e.stack));
            this.openReportResultLayer({
                title: "系统提示",
                content: "系统异常，请联系管理员",
                state: 0,
                time: 3
            });
        } finally {
            // 重置当前选择的业务
            this.currentBizInfo = null;
            // 重置缓存数据
            this.currentPatient = null;
        }
    }


    /**
     * 如果是多个业务，这里需要弹窗显示选择要办理的业务
     * 是否显示业务办理弹窗
     * @param params
     * @param isShow
     * @returns {boolean}
     */
    isShowBiz(params, isShow = false) {
        let self = this.catcheInfo;
        // 如果是多个业务，这里需要弹窗显示选择要办理的业务
        if (self.bizAttrList.length > 1 && self.currentBizInfo == null) {
            if (true === isShow) {
                // 拷贝
                let tempBizArray = JSON.parse(JSON.stringify(self.bizAttrList));
                tempBizArray.forEach((item) => {
                    item.params = params;
                });
                this.openBizReportLayer({
                    options: tempBizArray
                });
                return false;
            }
        }
        return true;
    }

    /**
     * 查询过程中 执行扫码查询
     * @param params
     */
    async reloadInitSign(params) {
        try {
            // 组装扫码参数
            let formData = this.getInitSignRequestParams(params);
            // 获取扫码数据
            this.openPopupLoading();
            const res = await UserCommitApi.initSign(formData);
            this.closePopupLoading();
            if (200 === parseInt(res.code)) {
                // 发送扫码数据
                await this.setReportPatientInfo(res);
            } else {
                // 暂无任何数据时候或者接口异常提示
                this.openReportResultLayer({
                    state: 0,
                    title: res.data && res.data.patientName ? res.data.patientName : "系统提示",
                    content: res.msg,
                });
            }
        } catch (e) {
            this.closePopupLoading();

            AndroidSDK.writeLog("扫码报到异常 initSign--->" + JSON.stringify(e.stack));
            this.openReportResultLayer({
                title: "系统提示",
                content: "系统异常，请联系管理员",
                state: 0
            });
        }
    }

    /**
     * 给视图模板需要展示的数据
     * @param res
     */
    async setReportPatientInfo(res) {
        let self = this.catcheInfo;

        if (objectIsEq(res, "String")) {
            res = JSON.parse(resetLongToStr(res));
        }
        // 处理之前先赋值为空 防止展示上一个的数据
        self.reportScreenData.numData = {};
        try {
            if (parseInt(res.code) === 200) {
                self.reportScreenData.numData = {
                    data: res.data,
                };

                // 给模板发送数据
                await this.setInitSignData(res);
            } else {
                // 暂无任何数据时候或者接口异常提示
                this.openReportResultLayer({
                    state: 0,
                    title: res.data && res.data.patientName ? res.data.patientName : "系统提示",
                    content: res.msg,
                });
            }
        } catch (e) {
            AndroidSDK.writeLog("setReportPatientInfo--->" + JSON.stringify(res));
            this.openReportResultLayer({
                title: "系统提示",
                content: "系统异常，请联系管理员",
                state: 0
            });
        }
    }

    /**
     * 给视图发送患者数据
     * @param res
     */
    setInitSignData(res) {
        let self = this.catcheInfo;
        try {
            const formRef = self.$refs["vFormRef"];
            if (formRef) {
                formRef.executeChildMethod(this.currentInfo?.id, "reportPatientInfo", res);
            }
        } catch (e) {
            self.handleException("sdkBizServices", "内部组件异常 -- reportPatientInfo -- >", JSON.stringify(e.stack));
        }
    }

    /**
     * 进入下级页面
     * @param item
     */
    async goToNext(item) {
        let self = this.catcheInfo;
        try {
            // 切换的业务
            self.currentBizInfo = item;

            await this.initSign(item.params, false);
            // 关闭弹窗
            this.closeBizReportLayer();
        } catch (e) {
            // 开启安卓读卡
            this.openReadCardScan();
            // 重置当前业务
            this.currentBizInfo = null;
        }
    }

    /**
     * 取号机 扫码
     * @param item
     */
    async goToInitSignBiz(item) {
        let self = this.catcheInfo;
        // 关闭安卓读卡
        this.cancelReadCardScan();
        // 重置业务
        self.currentBizInfo = item;

        if (self.currentPatient == null && "2" === item.tackNoType) {
            // 暂无任何数据时候或者接口异常提示
            this.openReportResultLayer({
                state: 0,
                title: "系统提示",
                content: "请刷卡取号",
                time: 5
            });
            return;
        }
        let formData = {
            patientNo: "",
            patientName: "",
        };
        // 设置缓存数据
        if (self.currentPatient != null && "2" === item.tackNoType) {
            formData.patientNo = this.currentPatient.patientNo || "";
            formData.patientName = this.currentPatient.patientName || "";
        }
        await this.initSignBiz(formData);
    }


    /**
     * 复诊报到
     * @param item
     */
    async repeatReport(item) {
        let self = this.catcheInfo;
        self.currentSignInfo.workerList = [item];
        // 报到
        await this.toReport(self.currentSignInfo);
    }

    /**
     * 银医自助一体机专用事件
     * @param data
     * @returns {Promise<void>}
     */
    async handleHiddenSubmit(data) {
        let self = this.catcheInfo;
        if (data && data.number) {
            let environment = AndroidSDK.environment;
            if (environment && 'dotnet' === environment) {
                // 判断是不是医保数据
                let number = data.number + "";
                if (number.startsWith("4243")) {
                    if (self.isOpenYiBao === false) {
                        // AndroidSDK.writeLog("暂未配置医保接口，如需使用医保码扫码，请联系分诊台");
                        if (self.patientNo === data.number) {
                            return;
                        }
                        self.patientNo = data.number;
                        self.currentInitParams = {
                            patientNo: data.number
                        }
                        await this.initSign(self.currentInitParams, true)
                        return;
                    }
                    let formJson = {
                        url: self.yiBaoInfo.url,
                        orgId: self.yiBaoInfo.orgId,
                        patientNo: data.number
                    }
                    AndroidSDK.getMedicalInsuranceData(JSON.stringify(formJson));
                    // 调用C端
                    return
                }
            }
            if (self.patientNo === data.number) {
                return;
            }
            self.patientNo = data.number;
            self.currentInitParams = {
                patientNo: data.number
            }
            // 调用扫码接口
            await this.initSign(self.currentInitParams, true)
        }
    }

    /**
     * 新余市中医院 特制逻辑
     * @param item
     * @returns {Promise<void>}
     */
    async reportDeptHandle(item) {
        let self = this.catcheInfo;
        try {
            // 获取排班墙数据
            const res1 = await XinYuShiCommitApi.changeRegisterObj([{
                registerId: item.registerId,
                registerObjId: item.registerObjId,
                registerObjName: item.registerObjName
            }]);
            if (200 === parseInt(res1.code)) {
                // 执行报到逻辑
                let formData = {
                    terminalId: this.deviceInfo.screenId,
                    terminalType: this.deviceInfo.screenType,
                    businessType: this.deviceInfo.businessType,
                    tenantId: this.deviceInfo.tenantId || '000000',
                    patientNo: self.currentParams.patientNo,
                    ruleType: item.ruleType || '0',
                    registerId: item.registerId,
                    signId: 0,
                    signType: 0,
                };

                this.openPopupLoading();
                // 获取模板详情
                const res = await UserCommitApi.signAction(formData);
                this.closePopupLoading();
                this.openReadCardScan();
                // 报到展示结果
                this.dealReportData(JSON.stringify(res))
                if (parseInt(res.code) === 200) {
                    // 重新扫码加载数据
                    await this.initSign({
                        patientNo: formData.patientNo
                    }, true);
                    // 给安卓发送报到成功标识
                    AndroidSDK.singleSignResult(res);
                    self.handleException('sdkServices', '单个报到返回结果 --> data', JSON.stringify(res));
                }
            }
        } catch (e) {
            AndroidSDK.writeLog("reportDeptHandle---> 报到失败" + JSON.stringify(e.stack));
        } finally {
            this.closeReportDept();
        }
    };

    /**
     * 桐乡市中医院 特制逻辑
     * @param item
     * @returns {Promise<void>}
     */
    async reportDRHandle(item) {
        let self = this.catcheInfo;
        try {
            // 将挂号记录中的医⽣更新为其选择的医⽣
            const res1 = await TongXiangShiCommitApi.changeRegisterObj([{
                registerId: item.registerId,
                workerId: item.workerId,
                workerName: item.workerName
            }]);
            if (200 === parseInt(res1.code)) {
                // 执行报到逻辑
                let formData = {
                    terminalId: this.deviceInfo.screenId,
                    terminalType: this.deviceInfo.screenType,
                    businessType: this.deviceInfo.businessType,
                    tenantId: this.deviceInfo.tenantId || '000000',
                    patientNo: self.currentParams.patientNo,
                    ruleType: item.ruleType || '0',
                    registerId: item.registerId,
                    signId: 0,
                    signType: 0,
                };
                this.openPopupLoading();
                // 获取模板详情
                const res = await UserCommitApi.signAction(formData);
                this.closePopupLoading();
                this.openReadCardScan();
                // 报到展示结果
                this.dealReportData(JSON.stringify(res));
                if (parseInt(res.code) === 200) {
                    // 重新扫码加载数据
                    await this.initSign({
                        patientNo: formData.patientNo
                    }, true);
                    // 给安卓发送报到成功标识
                    AndroidSDK.singleSignResult(res);
                    self.handleException('sdkServices', `单个报到返回结果${JSON.stringify(res)}`, );
                }
            }
        } catch (e) {
            AndroidSDK.writeLog(`reportDeptHandl报到失败${JSON.stringify(e.stack)}`);
        } finally {
            this.closeReportDR();
        }
    };

    /**
     * 报到机 单个报到
     * @param item
     */
    async toReport(item) {
        let self = this.catcheInfo;
        try {
            // 置空缓存
            self.currentSignInfo = {};
            switch (item.signType) {
                // 如果是复诊，并且要选择队列
                case "1" :
                    // 复诊的时候存在一个医生也不在线的情况
                    if (item.workerList && item.workerList.length > 0) {
                        // 只有一个的时候自动报到
                        if (item.workerList.length === 1) {
                            let formData = {
                                terminalId: this.deviceInfo.screenId,
                                terminalType: this.deviceInfo.screenType,
                                businessType: this.deviceInfo.businessType,
                                tenantId: this.deviceInfo.tenantId || "000000",
                                patientNo: self.reportScreenData.numData.data.patientNo,
                                ruleType: item.ruleType || "0",
                                registerId: item.qcRegister.registerId,
                                signId: item.qcRegister.signId,
                                signType: item.signType,
                                extendParams: item.extendParams,
                                medicalWorker: {
                                    workerId: item.workerList[0].workerId || "",
                                    workerName: item.workerList[0].workerName || "",
                                    registerObjId: item.workerList[0].registerObjId || "",
                                    registerObjName: item.workerList[0].registerObjName || ""
                                }
                            };
                            const res = await UserCommitApi.signAction(formData);
                            // 报到展示结果
                            this.dealReportData(JSON.stringify(res));
                            if (parseInt(res.code) === 200) {
                                // 重新扫码加载数据
                                await this.reloadInitSign({
                                    patientNo: self.reportScreenData.numData.data.patientNo
                                });
                                // 给安卓发送报到成功标识
                                AndroidSDK.singleSignResult(res);
                                self.handleException("sdkServices", `单个报到返回结果data${JSON.stringify(res)}`, );
                            }
                        } else {
                            // 赋值
                            self.currentSignInfo = item;

                            // 复诊时多个医生弹出选择一个医生进行报到
                            this.openReportDoctorLayer({
                                // 患者姓名
                                patientName: item.qcRegister.patientName,
                                // 医生
                                doctorList: item.workerList,
                                // 离线才会有值
                                workerOffLineTips: item.workerOffLineTips,
                                // 在线状态
                                workerOnLineStatus: item.workerOnLineStatus
                            });
                        }
                    } else {
                        // 提示无坐诊医生
                        this.openReportResultLayer({
                            state: 0,
                            title: "系统提示",
                            content: "无医生坐诊",
                        });
                    }
                    break;
                default:
                    // http://192.168.81.33:7000/clinic/api/qcss/sign/initSign
                    let autoSign = item.autoSign;
                    if (undefined !== autoSign && false === autoSign) {
                        // 医院标识
                        let hospitalCode = item.hospitalCode;

                        if ("新余市中医院" === hospitalCode) {
                            let registerObjFlag = item.registerObjFlag;
                            if ("通号" === registerObjFlag) {
                                await this.goToAction(item);
                                return
                            }
                        }

                        /**
                         * 特定报到逻辑--桐乡市中医医院
                         * 儿科在普通号首诊签到，以及回诊时可以按照自己的需求找对应医生报道，
                         * 该数据传到对应医生号别下，报道机上显示的医生队列为该科室在线登录叫号器的医生。离线的医生没办法签到和回诊
                         * @param item
                         */
                        if ("桐乡市中医医院" === hospitalCode) {
                            let registerObjFlag = item.registerObjFlag;
                            if ("通号" === registerObjFlag) {
                                await this.goToActionDr(item);
                                return
                            }
                        }

                        // 非预约时间报到确认弹窗
                        if (true === self.signInfo.NoETASure) {
                            // 判定是不是符合条件的
                            let hasEarly = item.qcRegister.hasEarly;
                            if (true === hasEarly) {
                                self.currentSignInfo = item;
                                // 非预约时间段内报到是否放弃预约优先权
                                this.openReportSurePower({});
                                return;
                            }
                        }

                    }

                    let formData = {
                        terminalId: this.deviceInfo.screenId,
                        terminalType: this.deviceInfo.screenType,
                        businessType: this.deviceInfo.businessType,
                        tenantId: this.deviceInfo.tenantId || "000000",
                        patientNo: self.reportScreenData.numData.data.patientNo,
                        ruleType: item.ruleType || "0",
                        registerId: item.qcRegister.registerId,
                        signId: item.qcRegister.signId,
                        signType: item.signType,
                        extendParams: item.extendParams,
                    };
                    this.openPopupLoading();
                    // 获取模板详情
                    const res = await UserCommitApi.signAction(formData);
                    this.closePopupLoading();
                    this.openReadCardScan();
                    // 报到展示结果
                    this.dealReportData(JSON.stringify(res));
                    if (parseInt(res.code) === 200) {
                        // 重新扫码加载数据
                        await this.reloadInitSign({
                            patientNo: self.reportScreenData.numData.data.patientNo
                        });
                        // 给安卓发送报到成功标识
                        AndroidSDK.singleSignResult(res);
                        self.handleException("sdkServices", "单个报到返回结果 --> data", JSON.stringify(res));
                    }
            }
        } catch (e) {
            self.handleException("sdkServices", "单个报到数据解析异常", JSON.stringify(e.stack));
        } finally {
        }
    }

    /**
     * 一键报到
     * 1 本地直接执行 2 用户点击执行，需要判定是否弹窗
     * @param data
     * @param isLocal
     * @returns {Promise<boolean>}
     */
    async reportAll(data, isLocal) {
        let self = this.catcheInfo;
        try {

            let {unSignList, signList} = data;
            let hasAutoRepeatSign = "0"; // 患者复诊自动报到
            // 开启拦截的话，执行这个逻辑
            if (self.layerNameKeySet.interceptSet.open === true) {
                // 拦截限制
                if (signList && unSignList && signList.length > 0 && unSignList.length === 0) {
                    // 提示暂无可报到的数据
                    this.openReportResultLayer({
                        state: 0,
                        title: self.layerNameKeySet.interceptSet.title,
                        content: self.layerNameKeySet.interceptSet.content,
                    });
                    return false;
                }
            }
            if ("1" === isLocal) {
                if (false === self.signInfo.autoReportAll && unSignList.length > 1) {
                    return false;
                }
            }
            // 复诊是否自动报到
            if (!hasAutoRepeatSign) {
                hasAutoRepeatSign = "1";
            }
            let signActionData = [];
            // 拦截数据 需要进行手动报到的数据
            let canActionData = [];
            // 只有初诊/过号
            for (let i = 0; i < unSignList.length; i++) {
                let item = unSignList[i];
                if (item.signType === '0' || item.signType === '2') {
                    // 初诊逻辑 二次判定
                    let autoSign = item.autoSign;
                    if (undefined !== autoSign && false === autoSign) {
                        canActionData.push(item);
                        continue;
                    }
                    signActionData.push({
                        registerId: item.qcRegister.registerId,
                        signType: item.signType,
                        signId: item.qcRegister.signId,
                        ruleType: item.ruleType || "0",
                        extendParams: item.extendParams
                    });
                }
                // 判定复诊 并且开启了复诊报到
                if (item.signType === '1' && "0" === hasAutoRepeatSign) {
                    // 复诊的时候存在一个医生也不在线的情况
                    if (item.workerList && item.workerList.length > 0 && item.workerList.length === 1) {
                        // 初诊逻辑 二次判定
                        let autoSign = item.autoSign;
                        if (undefined !== autoSign && false === autoSign) {
                            canActionData.push(item);
                            continue;
                        }
                        signActionData.push({
                            registerId: item.qcRegister.registerId,
                            signType: item.signType,
                            signId: item.qcRegister.signId,
                            ruleType: item.ruleType || "0",
                            extendParams: item.extendParams,
                            medicalWorker: {
                                workerId: item.workerList[0].workerId || "",
                                workerName: item.workerList[0].workerName || "",
                                registerObjId: item.workerList[0].registerObjId || "",
                                registerObjName: item.workerList[0].registerObjName || ""
                            }
                        });
                    }
                }
            }
            // =========== beg 特定报到机的逻辑 V2
            if (canActionData.length === 1 && this.currentInfo?.screenDataType.indexOf('keyboard-v2') > 0) {
                for (let i = 0; i < canActionData.length; i++) {
                    let item = canActionData[i];
                    let autoSign = item.autoSign;
                    if (undefined !== autoSign && false === autoSign) {
                        // 医院标识
                        let hospitalCode = item.hospitalCode;
                        if ("新余市中医院" === hospitalCode) {
                            let registerObjFlag = item.registerObjFlag;
                            if ("通号" === registerObjFlag) {
                                await this.goToAction(item);
                                return false;
                            }
                        }

                        if ("桐乡市中医医院" === hospitalCode) {
                            let registerObjFlag = item.registerObjFlag;
                            if ("通号" === registerObjFlag) {
                                await this.goToActionDr(item);
                                return false;
                            }
                        }
                        // 判定是不是符合条件的
                        let hasEarly = item.qcRegister.hasEarly;
                        if (true === hasEarly) {
                            // 非预约时间报到确认弹窗
                            if (true === self.signInfo.NoETASure) {
                                self.currentSignInfo = item;
                                // 非预约时间段内报到是否放弃预约优先权
                                this.openReportSurePower({});
                                return false;
                            } else {
                                signActionData.push({
                                    registerId: item.qcRegister.registerId,
                                    signType: item.signType,
                                    signId: item.qcRegister.signId,
                                    ruleType: item.ruleType || '0',
                                    extendParams: item.extendParams
                                });
                            }
                        }
                    }
                }
            } else {
                for (let i = 0; i < canActionData.length; i++) {
                    let item = canActionData[i];
                    // 是否早到
                    let hasEarly = item.qcRegister.hasEarly;
                    // 非预约时间报到确认弹窗
                    if (false === self.signInfo.NoETASure && true === hasEarly) {
                        signActionData.push({
                            registerId: item.qcRegister.registerId,
                            signType: item.signType,
                            signId: item.qcRegister.signId,
                            ruleType: item.ruleType || '0',
                            extendParams: item.extendParams
                        });
                    }
                }
            }
            // =========== end 特定报到机的逻辑 V2

            // 如果有初诊数据，则进行报到
            if (signActionData.length > 0) {
                let formData = {
                    terminalId: this.deviceInfo.screenId,
                    terminalType: this.deviceInfo.screenType,
                    businessType: this.deviceInfo.businessType,
                    tenantId: this.deviceInfo.tenantId || "000000",
                    patientNo: self.reportScreenData.numData.data.patientNo,
                    ruleType: this.deviceInfo.ruleType || "0",
                    signActionData: signActionData || []
                };

                this.openPopupLoading();
                const res = await UserCommitApi.signBatchAction(formData);
                this.closePopupLoading();

                // 报到展示结果
                this.dealReportData(res);

                if (parseInt(res.code) === 200) {
                    // 重新扫码加载数据
                    await this.reloadInitSign({
                        patientNo: self.reportScreenData.numData.data.patientNo
                    });

                    // 给安卓发送报到成功标识 -- 安卓会根据相关数据 执行打印逻辑
                    AndroidSDK.batchSignResult(res);
                    self.handleException("sdkServices", "批量报到返回结果 --> data", JSON.stringify(res));
                }

            } else {
                //
                if ("2" === isLocal) {
                    // 提示暂无可报到的数据
                    this.openReportResultLayer({
                        state: 0,
                        title: "系统提示",
                        content: "请点击对应挂号信息的报到按钮完成取号",
                    });
                }
            }
        } catch (e) {
            self.handleException("sdkServices", "批量报到异常 --> error", JSON.stringify(e.stack));
        } finally {

        }
    }

    /**
     * 指定特定报到逻辑
     * @param item
     */
    async goToAction(item) {
        let self = this.catcheInfo;
        try {
            // 先查询数据
            // 获取接口数据
            // 获取排班墙数据
            const formJson = this.getInitSignRequestParams({
                patientNo: self.reportScreenData.numData.data.patientNo
            });
            const res2 = await XinYuShiCommitApi.getDeptOnlineRegisterObj(formJson)
            if (200 === parseInt(res2.code)) {
                // 组装数据
                self.currentParams = {
                    patientNo: self.reportScreenData.numData.data.patientNo,
                    qcRegister: item
                };
                this.openReportDept({
                    signList: [item.qcRegister],
                    deptList: res2.data
                })
            }
        } catch (e) {
            console.log(e.stack)
        }
    }


    /**
     * 特定报到逻辑--桐乡市中医医院
     * 儿科在普通号需选择对应医生报道，
     * 该数据传到对应医生号别下，报道机上显示的医生队列为该科室在线登录叫号器的医生。离线的医生没办法签到和回诊
     * @param item
     */
    async goToActionDr(item) {
        let self = this.catcheInfo;
        let {qcRegister} = item;
        try {
            let params = Object();
            Reflect.set(params,'registerId',(qcRegister.registerId))
            Reflect.set(params,'registerObjId',(qcRegister.registerObjId))
            Reflect.set(params,'registerObjType',(qcRegister.registerObjType))
            Reflect.set(params,'registerObjName',(qcRegister.registerObjName))
            // 查询挂号的号别所属科室下所有的医⽣--弹层选择医生
            const {code,data} = await TongXiangShiCommitApi.getDROnlineRegisterObj(params);
            if (parseInt(code) === 200) {
                // 组装数据请求的参数
                self.currentParams = {
                    patientNo: self.reportScreenData.numData.data.patientNo,
                    qcRegister: qcRegister || Object()
                };
                // 调用弹层--打开医生弹层
                // item.qcRegister 患者信息
                this.openReportDR({
                    patientInfo: {...qcRegister},
                    DRList: (data.registerObjWorkerList),
                })
            }else {
                return false
            }
        } catch (e) {
            console.log(e.stack)
        }
    }

    /**
     * 报到展示结果
     * @param res
     */
    dealReportData(res) {
        let self = this.catcheInfo;
        try {
            if (objectIsEq(res, "String")) {
                res = JSON.parse(resetLongToStr(res));
            }
            if (parseInt(res.code) === 200) {
                const {data, code} = res;
                let arr;
                // 单个报到
                if (objectIsEq(data, "Object")) {
                    data.status = code;
                    arr = [data];
                } else {
                    // 多个报到
                    arr = data;
                    if (arr.length > 0) {
                        data.patientName = arr[0].patientName;
                    }
                }
                if (arr.length > 0) {
                    // 打开报到成功患者列表
                    this.openReportPatientLayer({
                        patientNumberList: arr,
                        patientName: data.patientName || ""
                    });
                } else {
                    this.openReportResultLayer({
                        state: 0,
                        title: "系统提示",
                        content: "未查询到报到信息",
                    });
                }
            } else {
                // 报到失败弹窗
                this.openReportResultLayer({
                    title: res.data && res.data.patientName ? res.data.patientName : "系统提示",
                    content: res.msg,
                    state: 0
                });
            }
        } catch (e) {
            self.handleException("dealReportDataError:", "解析错误", JSON.stringify(e.stack));
            AndroidSDK.writeLog("dealReportData:" + JSON.stringify(res));
            this.openReportResultLayer({
                state: 0,
                title: "系统提示",
                content: "系统异常，请联系管理员",
            });

        }
    }

    /**
     * 关闭键盘
     */
    closeKeyboard() {
        let self = this.catcheInfo;
        // 判定要不要关闭键盘
        if (this.currentInfo.screenDataType.indexOf("reportAuto") > -1) {
            // 关闭键盘
            try {
                const formRef = self.$refs["vFormRef"];
                if (formRef) {
                    formRef.executeChildMethod(this.currentInfo?.id, "reportCloseLayer");
                }
            } catch (e) {
                self.handleException("sdkBizServices", "内部组件异常 -- reportCloseLayer -- >", JSON.stringify(e.stack));
            }
        }
    }


    /**
     * 开启安卓的读卡器
     */
    openReadCardScan() {
        AndroidSDK.reportSDKServices("readCardNoLimit");
    }

    /**
     * 关闭安卓的读卡器
     */
    cancelReadCardScan() {
        AndroidSDK.reportSDKServices("cancelNoLimitReadCard");
    }

    /**
     * 全局消息弹窗
     * @param obj 消息对象
     */
    openReportResultLayer(obj) {
        let self = this.catcheInfo;
        self.reportResultInfo.info = Object.assign(self.reportResultInfo.info, obj);
        self.reportResultInfo.visible = true;
    }

    /**
     * 全局弹窗关闭
     */
    closeReportResultLayer() {
        let self = this.catcheInfo;
        self.reportResultInfo.visible = false;
        // 开启安卓读卡监控
        this.openReadCardScan();
        // 重置缓存数据
        self.currentPatient = null;
    }

    /**
     * 返回首页
     */
    goHomePage() {
        let self = this.catcheInfo;
        // 回到首页
        try {
            const formRef = self.$refs["vFormRef"];
            if (formRef) {
                formRef.executeChildMethod(this.currentInfo?.id, "reportBack");
            }
        } catch (e) {
            self.handleException("sdkBizServices", "内部组件异常 -- goHomePage -- >", JSON.stringify(e.stack));
        }
    }

    /**
     * 复诊医生弹窗
     * @param obj 消息对象
     */
    openReportDoctorLayer(obj) {
        let self = this.catcheInfo;
        self.reportDoctorInfo.info = Object.assign(self.reportDoctorInfo.info, obj);
        self.reportDoctorInfo.visible = true;
    }

    /**
     * 关闭复诊医生弹窗
     */
    closeReportDoctorLayer() {
        let self = this.catcheInfo;
        self.reportDoctorInfo.visible = false;
    }

    /**
     * 非预约时间报到确认弹窗
     * report-sure-power
     */

    openReportSurePower(obj) {
        let self = this.catcheInfo;
        self.reportSurePowerInfo.info = Object.assign(self.reportSurePowerInfo.info, obj);
        self.reportSurePowerInfo.visible = true;
    }

    /**
     * 关闭非预约时间报到确认弹窗
     */
    closeReportSurePower() {
        let self = this.catcheInfo;
        self.reportSurePowerInfo.visible = false;
    }

    /**
     * 选择科室开启弹窗
     * @param obj
     */
    openReportDept(obj) {
        let self = this.catcheInfo;
        self.reportDeptInfo.info = Object.assign(self.reportDeptInfo.info, obj);
        self.reportDeptInfo.visible = true;
    }

    /**
     * 选择科室关闭弹窗
     */
    closeReportDept() {
        let self = this.catcheInfo;
        self.reportDeptInfo.visible = false;
    }


    /**
     * 选择医生开启弹窗
     * @param obj
     */
    openReportDR(obj) {
        let self = this.catcheInfo;
        self.reportDRInfo.info = Object.assign(self.reportDRInfo.info, obj);
        self.reportDRInfo.visible = true;
    }

    /**
     * 选中医生关闭弹窗
     * @param obj
     */
    closeReportDR() {
        let self = this.catcheInfo;
        self.reportDRInfo.visible = false;
    }

    /**
     * 报到成功弹窗
     * @param obj 消息对象
     */
    openReportPatientLayer(obj) {
        let self = this.catcheInfo;
        self.reportPatientInfo.info = Object.assign(self.reportPatientInfo.info, obj);
        self.reportPatientInfo.visible = true;
    }

    /**
     * 关闭报到成功
     */
    closeReportPatientLayer() {
        let self = this.catcheInfo;
        // 开启安卓读卡监控
        self.reportPatientInfo.visible = false;
    }

    /**
     * 打开业务报到
     * @param obj 消息对象
     */
    openBizReportLayer(obj) {
        let self = this.catcheInfo;
        self.bizReportLayerInfo.info = Object.assign(self.bizReportLayerInfo.info, obj);
        self.bizReportLayerInfo.visible = true;
    }

    /**
     * 关闭业务报到
     */
    closeBizReportLayer() {
        let self = this.catcheInfo;
        self.bizReportLayerInfo.visible = false;
        // 开启安卓读卡监控
        self.openReadCardScan();
        // 重置当前选择的业务
        self.currentBizInfo = null;
        // 重置缓存数据
        self.currentPatient = null;
    }

    /**
     * 打开loading
     */
    openPopupLoading() {
        let self = this.catcheInfo;
        self.popupLoadingInfo.visible = true;
    }

    /**
     * 关闭Loading
     */
    closePopupLoading() {
        let self = this.catcheInfo;
        self.popupLoadingInfo.visible = false;
    }

}

export {MachineObserverBiz};
